package com.moleq.device.printer;

import com.epson.epsonio.DevType;
import com.epson.epsonio.EpsonIo;
import com.epson.epsonio.EpsonIoException;
import com.epson.epsonio.IoStatus;
import com.moleq.device.DeviceUtil;

public class EsponWifiPrinter extends Printer {

	private String mIpAddress = "";
	private int mPort = 0;
	private EpsonIo mEpsonPort = null;
	private int mInterface;

	public EsponWifiPrinter() {
		mEpsonPort = new EpsonIo();
		mInterface = DevType.TCP;

		lineWidth = 42;
	}

	public void setIpAddress(String ip, int port) {
		mIpAddress = ip;
		mPort = port;

	}

	
	@Override
	public void print(String buffer) {
		mIsBusy = true;

//		String endCharacter = buffer + "\r\n";
//		byte[] data = endCharacter.getBytes();
		byte[] data = buffer.getBytes();
		int offset = 0; // It outputs from the head of a buffer.
		int size = data.length; // The size of output data is set up.
		int timeout = 5000; // The longest waiting time is set as 5 seconds.

		try {
			mEpsonPort.write(data, offset, size, timeout);
			ResponseMsg = "SEND SUCCESS";
		} catch (EpsonIoException e) {
			dispErrStatus(e.getStatus());
		}

		mIsBusy = false;

	}

	@Override
	public String getPrinterName() {
		// TODO Auto-generated method stub
		return Printer.EPSON_WIRELESS_PRINTER;
	}

	@Override
	public void open() {
		try {
			mEpsonPort.open(mInterface, mIpAddress, null);
			ResponseMsg = "OPEN SUCCESS";
			mIsAvailable = true;
		} catch (EpsonIoException e) {
			mIsAvailable = false;
			dispErrStatus(e.getStatus());
		}

	}

	@Override
	public void close() {
		mIsAvailable = false;
		
		try {
			mEpsonPort.close();
			ResponseMsg = "CLOSE SUCCESS";
		} catch (EpsonIoException e) {
			dispErrStatus(e.getStatus());
		}

	}

	@Override
	public void cutPaper() {
		// TODO Auto-generated method stub
//		String s = DeviceUtil.numberString2Char("27");
//		this.print(s+"|fP");
	}

	private void dispErrStatus(int errStatus) {
		switch (errStatus) {

		case IoStatus.ERR_PARAM:
			ResponseMsg = "PARAMETER ERROR";
			break;

		case IoStatus.ERR_OPEN:
			ResponseMsg = "OPEN ERROR";
			break;

		case IoStatus.ERR_CONNECT:
			ResponseMsg = "CONNECT ERROR";
			break;

		case IoStatus.ERR_TIMEOUT:
			ResponseMsg = "TIMEOUT ERROR";
			break;

		case IoStatus.ERR_MEMORY:
			ResponseMsg = "MEMORY ERROR";
			break;

		case IoStatus.ERR_ILLEGAL:
			ResponseMsg = "ILLEGAL ERROR";
			break;

		case IoStatus.ERR_PROCESSING:
			ResponseMsg = "PROCESSING ERROR";
			break;

		default:
			ResponseMsg = "ERROR FAILURE";
			break;
		}

	}

	

}
